<template>
  <div class="app-container">
    <div style="display:flex;justify-content:space-between;align-items: center;">
      <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="queryParams.realName" placeholder="请输入员工姓名" clearable size="small" style="width: 150px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="工号" prop="userSn">
          <el-input v-model="queryParams.userSn" placeholder="请输入员工工号" clearable size="small" style="width: 150px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
          <el-button size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div style="text-align:right;margin-bottom: 22px;">
        <el-button-group slot="reference">
          <el-button size="small" icon="el-icon-refresh" @click="getList" />
          <el-button size="small" icon="el-icon-plus" @click="handelAdd">添加</el-button>
        </el-button-group>
      </div>
    </div>

    <el-table v-loading="loading" border :data="userList" @sort-change="sortChange">
      <el-table-column label="编号" prop="id" width="100" align="center" />
      <el-table-column label="微信昵称" align="center" prop="vxName" />
      <el-table-column label="姓名" align="center" prop="realName" />
      <el-table-column label="工号" align="center" prop="userSn" />
      <el-table-column label="手机号" align="center" prop="phone"></el-table-column>
      <el-table-column label="更新时间" align="center" prop="modifyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleUpdate(scope.row)">修改信息</el-button>
          <el-button size="mini" type="text" icon="el-icon-upload" @click="handleUpload(scope.$index)">上传</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handlePic(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-lock" @click="handlePermis(scope.row)">权限</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 预览头像 -->
    <el-dialog v-dialogDrag :visible.sync="picOpen" :title="picTitle" width="800" append-to-body>
      <img :src="facePic" style="display: block; max-width: 50%; max-height: 100%; margin: 0 auto;">
    </el-dialog>

    <!-- 上传头像 -->
    <el-dialog v-dialogDrag :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body>
      <div style="height: 300px;display: flex; align-items: center;justify-content: center;">
        <el-upload ref="upload" :limit="1" accept=".jpg, .png, .jpeg" drag :headers="upload.headers"
          :action="upload.url" :before-upload="beforeFileUpload" :on-success="handleUploadSuccess"
          :show-file-list="false" :file-list="upload.fileList">
          <el-image v-if="upload.imageUrl" :src="upload.imageUrl" class="upload-img" fit="scale-down"></el-image>
          <div v-if="!upload.imageUrl" class="upload-hint-wrap">
            <i class="el-icon-upload avatar-uploader-icon"></i>
            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
          </div>
          <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入 jpg、png、jpeg 格式文件！</div>
        </el-upload>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog v-dialogDrag class="form_dialog" :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入员工姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工号" prop="userSn">
              <el-input v-model="form.userSn" placeholder="请输入员工工号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入员工手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门禁密码" prop="doorPwd">
              <el-input v-model="form.doorPwd" placeholder="请输入员工开门密码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getFile,
  setAvatar,
  getUser,
  updateUser,
  addUser,
  delUser
} from "@/api/gate/user";
import { getToken } from "@/utils/auth";

export default {
  name: "Role",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房间表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //预览显示
      picOpen: false,
      picTitle: undefined,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 20,
        realName: undefined,
        userSn: undefined,
      },

      //图片预览
      facePic: '',
      // 上传参数
      upload: {
        open: false, // 是否显示弹出层
        title: "", // 弹出层标题
        imageUrl: '',
        fileList: [],
        fileBid: undefined,
        url: process.env.VUE_APP_BASE_API + '/api/' + "system/file/upload/single", // 请求地址
        headers: { Authorization: "Bearer " + getToken() }, // 设置上传的请求头部
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        realName: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" }
        ],
        userSn: [
          { required: true, message: "员工工号不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "员工手机号不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.reset()
    this.getList();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(
        response => {
          this.userList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    sortChange(column, prop, order) {
      if (column.order === 'ascending') {
        this.queryParams.orderBy = column.prop + ' ' + 'asc'
      } else if (column.order === 'descending') {
        this.queryParams.orderBy = column.prop + ' ' + 'desc'
      } else {
        this.queryParams.orderBy = ''
      }
      this.getList()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看照片 */
    handlePic(row) {
      if (!row.fileBid) {
        this.msgError("未上传人脸照片")
        return
      }
      getFile(row.fileBid).then(
        response => {
          if (response.data && response.data.fileUrl) {
            this.facePic = process.env.VUE_APP_BASE_API + response.data.fileProxyPath
            this.picOpen = true
            this.picTitle = row.realName
          } else {
            this.msgError("人脸照片不存在")
          }
        }
      )
    },
    /**人员权限 */
    handlePermis(row) {
      this.$router.push({
        path: '/permis/' + row.id
      });
    },
    /**人员删除 */
    handleDelete(row, index) {
      let rId = row.id
      if (!rId) {
        return
      }
      this.$confirm('是否确认移除编号为"' + row.id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delUser(row.id)
      }).then(() => {
        this.userList.splice(index, 1)
        this.msgSuccess("移除成功");
      })
    },

    /** 上传操作 */
    handleUpload(index) {
      console.log('handleUpload', index)
      this.upload.open = true;
      this.upload.curUploadIndex = index;
      this.upload.imageUrl = undefined
      this.upload.fileBid = undefined

      let row = this.userList[index]
      this.upload.title = row.realName;
    },

    beforeFileUpload(file) {
      const isJPG = (file.type == 'image/jpeg' || file.type == 'image/jpg' || file.type == 'image/png');
      const isLt2M = file.size / 1024 < 200;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 200KB!');
      }

      const _URL = window.URL || window.webkitURL
      const isSize = new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = function () {
          this.width > 1280 || this.height > 1280 ? reject() : resolve()
        }
        img.src = _URL.createObjectURL(file)
      }).then(
        () => {
          return file
        },
        () => {
          this.$message.error('上传头像图片分辨率不能超过1280*1280！')
          return Promise.reject()
        }
      )

      return isJPG && isLt2M && isSize;
    },

    /** 文件上传成功处理 */
    handleUploadSuccess(response, file, fileList) {
      console.log('handleFileSuccess:', response)
      this.upload.fileBid = response.data.fileBid
      this.upload.imageUrl = URL.createObjectURL(file.raw);

      this.upload.fileList = []
    },
    //保存用户头像
    submitUpload() {
      let curIndex = this.upload.curUploadIndex
      if (curIndex == undefined || curIndex == null) {
        return
      }
      let cur = this.userList[curIndex]
      if (!cur || !this.upload.fileBid) {
        return
      }
      setAvatar(cur.id, this.upload.fileBid).then(response => {
        // 清理
        this.upload.open = false;
        this.$refs.upload.clearFiles();
        // 提示成功，并刷新
        this.msgSuccess("上传成功");
        this.userList[curIndex].fileBid = this.upload.fileBid

        console.log('setAvatar,', this.userList)
      })
    },

    // 表单重置
    reset() {
      this.form = {
        realName: undefined,
        userSn: undefined,
        phone: undefined,
        doorPwd: undefined,
      };
      this.resetForm("form");
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;

        let name = this.form.vxName || this.form.realName || ''
        this.title = name;
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateUser(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    //添加人员
    handelAdd() {
      this.reset();
      this.open = true;
      this.title = "添加临时人员";
    }
  }
};
</script>
<style>
.el-upload-dragger {
  height: 300px;
}

.upload-hint-wrap {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-img {
  width: 295px;
  height: 295px;
}
</style>